package com.neusoft.elmboot.config;

import com.neusoft.elmboot.common.Constants;
import com.neusoft.elmboot.exception.CustomAccessDeniedHandler;
import com.neusoft.elmboot.filter.JwtFilter;
import com.neusoft.elmboot.filter.JwtLoginFilter;
import com.neusoft.elmboot.service.impl.MyUserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("myUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;
    
//   @Override
//   @Bean
//   public AuthenticationManager authenticationManagerBean() throws Exception {
//        return super.authenticationManagerBean();
//   }
    
   @Bean
   PasswordEncoder passwordEncoder() {
     return NoOpPasswordEncoder.getInstance();
//     return new BCryptPasswordEncoder();
   }


   @Override 
   protected void configure(AuthenticationManagerBuilder auth) throws Exception
   { 
//     auth.inMemoryAuthentication().withUser("admin")
//         .password("123").roles("admin")
//         .and()
//         .withUser("sang")
//         .password("456")
//         .roles("user");

       auth.userDetailsService(userDetailsService)
       .passwordEncoder(passwordEncoder());

   } 

   @Override 
   protected void configure(HttpSecurity http) throws Exception {
       // 定义拒绝访问的具体处理逻辑和返回页面内容
       http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

     http.authorizeRequests() 
//         .antMatchers("/admin").hasRole("admin")
         .antMatchers(Constants.IGNORE_AUTHORIZE_URLS).permitAll()
//             .antMatchers("/**").permitAll()
//             .antMatchers("/food/list").hasRole("user")
         .anyRequest().authenticated()
             .and().
             cors()
             .and()
             .formLogin()
//             .loginPage("/login")
             .loginProcessingUrl("/user/login")
             .usernameParameter("userId")
             .passwordParameter("password")
//             .failureUrl("/error")
             .failureHandler(new AuthenticationFailureHandler() {
                 @Override
                 public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp,
                                                     AuthenticationException e) throws IOException, ServletException {
                     log.info("------onAuthenticationFailure(): reqUrl:"+req.getRequestURI());
                     e.printStackTrace();
                 }
             })
         .and()
         .addFilterBefore(new JwtLoginFilter("/user/login",authenticationManager()), UsernamePasswordAuthenticationFilter.class)
         .addFilterBefore(new JwtFilter(),UsernamePasswordAuthenticationFilter.class)
         .csrf().disable(); 
   }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/upload/**","/geneCode",
                        "/business/listBusinessByOrderTypeId","/business/detail",
                        "/food/listFoodByBusinessId","/CartController/listCart",
                        "/css/**", "/js/**","/CartController/**","/OrdersController/**","/DeliveryAddressController/**");
    }
} 